package com.diet.web.controller.diet;

import com.diet.common.annotation.Anonymous;
import com.diet.common.core.controller.BaseController;
import com.diet.common.core.domain.AjaxResult;
import com.diet.common.core.page.TableDataInfo;
import com.diet.system.domain.DietUserBehavior;
import com.diet.system.service.IDietUserBehaviorService;
import com.diet.system.service.IDietUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户行为Controller
 */
@Anonymous
@RestController
@RequestMapping("/diet")
@CrossOrigin(origins = "*")
public class UserBehaviorController extends BaseController {
    @Autowired
    private IDietUserBehaviorService dietUserService;

    /**
     * 收藏/取消收藏菜品
     */
    @Anonymous
    @PostMapping("/favorite")
    public AjaxResult toggleFavorite(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Long dishId = Long.valueOf(params.get("dishId").toString());
            System.out.println("favorite：" + userId + " " + dishId);
            // 调用service实现收藏/取消收藏逻辑
            boolean isFavorited = dietUserService.toggleFavorite(userId, dishId);

            Map<String, Object> result = new HashMap<>();
            result.put("isFavorited", isFavorited);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }



    /**
     * 获取收藏列表
     */
    @Anonymous
    @GetMapping("/favorites/{userId}")
    public TableDataInfo getFavorites(@PathVariable("userId") Long userId) {
        startPage();
        // 调用service获取真实收藏数据
        List<?> favorites = dietUserService.selectUserFavorites(userId);
        System.out.println("=== 收藏列表调试信息 ===");
        System.out.println("用户ID: " + userId);
        System.out.println("数据条数: " + favorites.size());
        
        // 打印每个收藏项的详细信息
        for (int i = 0; i < favorites.size() && i < 3; i++) {
            Object item = favorites.get(i);
            System.out.println("第" + (i+1) + "个收藏项: " + item);
            System.out.println("数据类型: " + item.getClass().getName());
            
            if (item instanceof com.diet.system.domain.DietUserBehavior) {
                com.diet.system.domain.DietUserBehavior behavior = (com.diet.system.domain.DietUserBehavior) item;
                System.out.println("  dishId: " + behavior.getDishId());
                System.out.println("  dishName: " + behavior.getDishName());
                System.out.println("  imgUrl: " + behavior.getImgUrl());
                System.out.println("  cuisine: " + behavior.getCuisine());
                System.out.println("  calories: " + behavior.getCalories());
            }
        }
        
        TableDataInfo result = getDataTable(favorites);
        System.out.println("返回结果: " + result);
        System.out.println("=== 调试信息结束 ===");
        return result;
    }

    /**
     * 菜品评分
     */
    @Anonymous
    @PostMapping("/rate")
    public AjaxResult rateDish(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Long dishId = Long.valueOf(params.get("dishId").toString());
            System.out.println("rate：" + userId + " " + dishId );


            Integer rating = Integer.valueOf(params.get("rating").toString());
            // 检查用户是否已对该菜品进行过评分
            boolean hasRated = dietUserService.hasUserRated(userId, dishId);
            if (hasRated) {
                return AjaxResult.error("您已对该菜品进行过评分，无法重复评分");
            }
            // 调用service实现评分逻辑
            boolean success = dietUserService.rateDish(userId, dishId, rating);
            System.out.println("rate：" + userId + " " + dishId + " " + rating);
            return success ? AjaxResult.success("评分成功") : AjaxResult.error("评分失败");
        } catch (Exception e) {
            return AjaxResult.error("评分失败：" + e.getMessage());
        }
    }
    /**
     * 查询用户已评分的菜品
     */
    @Anonymous
    @GetMapping("/ratings/{userId}")
    public TableDataInfo getUserRatings(@PathVariable("userId") Long userId) {
        startPage();
        List<DietUserBehavior> ratings = dietUserService.selectUserRatings(userId);
        System.out.println("getUserRatings：" + ratings);
        return getDataTable(ratings);
    }
    /**
     * 记录菜品点击行为
     */
    @Anonymous
    @PostMapping("/click")
    public AjaxResult clickDish(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Long dishId = Long.valueOf(params.get("dishId").toString());

            // 调用service实现点击记录逻辑
            boolean success = dietUserService.clickDish(userId, dishId);
            System.out.println("click：" + userId + " " + dishId);
            return success ? AjaxResult.success("点击记录成功") : AjaxResult.error("点击记录失败");
        } catch (Exception e) {
            return AjaxResult.error("点击记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户点击历史
     */
    @Anonymous
    @GetMapping("/clicks/{userId}")
    public TableDataInfo getUserClicks(@PathVariable("userId") Long userId) {
        startPage();
        List<DietUserBehavior> clicks = dietUserService.selectUserClicks(userId);
        System.out.println("getUserClicks：" + clicks);
        return getDataTable(clicks);
    }
    
    /**
     * 获取用户对菜品的状态（收藏、评分）
     */
    @Anonymous
    @PostMapping("/status/{userId}")
    public AjaxResult getUserDishStatus(@PathVariable("userId") Long userId, @RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<Object> dishIdsObj = (List<Object>) params.get("dishIds");
            List<Long> dishIds = dishIdsObj.stream()
                .map(obj -> Long.valueOf(obj.toString()))
                .collect(java.util.stream.Collectors.toList());
            
            System.out.println("获取用户状态: userId=" + userId + ", dishIds=" + dishIds);
            
            Map<String, Object> result = dietUserService.getUserDishStatus(userId, dishIds);
            System.out.println("状态结果: " + result);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取状态失败：" + e.getMessage());
        }
    }

}
